﻿Imports Microsoft.VisualBasic
Imports System.Net.Mail
Imports System.Data.SqlClient
Imports System.Security.Cryptography
Imports System.Data
Imports System
Imports System.IO
Imports System.Text
Imports log4net
Imports System.Xml
Imports System.Web.Configuration.WebConfigurationManager
Imports System.Collections.Generic
Imports System.Net

Public Class Util
    Inherits System.Web.UI.Page
    Private Shared ReadOnly log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

    'Public Shared Sub SavePreReservationName(ByVal tripid As Integer, ByVal name As String)
    '    Dim sSQL As String = ""
    '    sSQL = "UPDATE CustomerResDetailLine SET [Name] = @Name WHERE TripID = @TripID"
    '    Dim myConnection As New SqlConnection(Connection.ConnectionString)
    '    Dim myCommand As New SqlCommand(sSQL, myConnection)
    '    myCommand.Parameters.AddWithValue("@TripID", tripid)
    '    myCommand.Parameters.AddWithValue("@Name", name)

    '    myConnection.Open()
    '    myCommand.ExecuteNonQuery()
    '    myConnection.Close()

    'End Sub

    'Public Shared Function getMeetGreetFromTableAirports(ByVal airportCode As String) As String
    '    Dim meetgreet As String = ""
    '    Dim cmd As New SqlCommand("dbo.spGetMeetGreetFromTableAirports", Connection.GetConnection())
    '    cmd.CommandType = CommandType.StoredProcedure
    '    cmd.Parameters.Add(New SqlParameter("@airportCode", SqlDbType.NVarChar, 10)).Value = airportCode
    '    Dim dr As SqlDataReader
    '    dr = cmd.ExecuteReader()
    '    While dr.Read()
    '        meetgreet = dr("Meet_Greet").ToString()
    '    End While
    '    dr.Close()
    '    Connection.Close()
    '    Return meetgreet
    'End Function

    'Public Shared Function getSeeNotesFromTableAirports(ByVal airportCode As String) As String
    '    Dim notes As String = ""
    '    Dim cmd As New SqlCommand("dbo.spGetSeeNotesFromTableAirports", Connection.GetConnection())
    '    cmd.CommandType = CommandType.StoredProcedure
    '    cmd.Parameters.Add(New SqlParameter("@airportCode", SqlDbType.NVarChar, 10)).Value = airportCode
    '    Dim dr As SqlDataReader
    '    dr = cmd.ExecuteReader()
    '    While dr.Read()
    '        notes = dr("Notes").ToString()
    '    End While
    '    dr.Close()
    '    Connection.Close()
    '    Return notes
    'End Function


    Public Shared Function IsEmail(ByVal testEmail As String) As Boolean
        Dim validator As New Regex("^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$")
        If validator.IsMatch(testEmail.ToLower()) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function validateZip(ByVal testZip As String) As Boolean
        Dim validator As New Regex("\d{5}")
        If validator.IsMatch(testZip) Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Shared Function IsZip(ByVal testZip As String) As Boolean
        Dim validator As New Regex("^[0-9a-zA-Z]+$")
        If validator.IsMatch(testZip) Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Shared Function FormatTime(ByVal time As String) As String
        Dim sHour As String = time.Substring(0, 2)
        Dim sMinute As String = time.Substring(3, 2)
        Dim sResult As String

        If CInt(sHour) >= 12 Then
            sResult = IIf(CInt(sHour) - 12 >= 10, CStr(CInt(sHour) - 12), "0" + CStr(CInt(sHour) - 12))
            sResult += ":" + sMinute + " PM"
        Else
            sResult = sHour
            sResult += ":" + sMinute + " AM"
        End If
        Return sResult
    End Function
    Public Shared Function FormatDate(ByVal vDate As String) As String
        Dim sResult As String
        sResult = vDate.Substring(5, 2) + "/" + vDate.Substring(8, 2) + "/" + vDate.Substring(0, 4)
        Return sResult
    End Function

  
    Public Shared Function SendFax(ByVal faxNum As String, ByVal message As String) As Boolean
        Return True
    End Function
    Public Shared Function GenerateCustomerId() As Int32
        Return GenerateId("CUSTOMER", "CustomerId")
    End Function
    Public Shared Function GenerateId(ByVal tableName As String, ByVal columnName As String) As Int32
        Dim iID As Integer = 0

        While iID = 0
            Dim randomClass As New Random()
            iID = randomClass.[Next](100000, 999999)
            Dim sSQL As String = "select * from " + tableName + " where " + columnName + " = '" + iID.ToString + "'"

            Dim reader As SqlDataReader = Connection.ExcuteReader(sSQL)
            If reader.Read() Then
                iID = 0
            End If
            reader.Close()
            Connection.Close()
        End While
        Return iID
    End Function
    Public Shared Function CreateRandomPassword(ByVal len As Integer) As String
        Dim table As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        Dim tableNumber As String = "1234567890"
        Dim result As String = ""
        Dim rand As New Random()
        Dim pwdtmp As Integer
        For i As Integer = 0 To len - 2
            pwdtmp = rand.[Next](table.Length)
            result += table(pwdtmp)
        Next
        pwdtmp = rand.[Next](tableNumber.Length)
        result += tableNumber(pwdtmp)
        Return result
    End Function
    Public Shared Function EscapeQuotes(ByVal sInput As String) As String
        sInput = sInput.Replace("'", "''")
        Return sInput
    End Function
    Public Shared Function EscapeQuotes_1(ByVal sInput As String) As String
        sInput = sInput.Replace("''", "'")
        Return sInput
    End Function

    Public Shared Function GetMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5CryptoServiceProvider object.
        Dim md5Hasher As MD5 = MD5.Create
        ' Convert the input string to a byte array and compute the hash.
        Dim data() As Byte = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))
        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As StringBuilder = New StringBuilder
        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer = 0
        Do While (i < data.Length)
            sBuilder.Append(data(i).ToString("x2"))
            i = (i + 1)
        Loop
        ' Return the hexadecimal string.
        Return sBuilder.ToString
    End Function

    ' Verify a hash against a string.
    Public Shared Function VerifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = GetMd5Hash(input)
        ' Create a StringComparer an comare the hashes.
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
        If (0 = comparer.Compare(hashOfInput, hash)) Then
            Return True
        Else
            Return False
        End If
    End Function


    Public Shared Function PhoneFormat(ByVal phone As String) As String
        If Len(phone) > 0 Then
            phone = FilterPhone(phone)
        Else
            Return ""
        End If
        If Left(phone, 1) = "0" Then
            PhoneFormat = phone
        Else
            PhoneFormat = "(" & Left(phone, 3) & ") " & Mid(phone, 4, 3) & "-" & Right(phone, 4)
        End If
    End Function

    Public Shared Function FilterPhone(ByVal phone As String) As String
        Dim result As String = ""
        Dim iCtr As Integer = 0
        Dim sValidString As String = "0123456789"

        phone = phone.Trim
        If Left(phone, 1).Equals("+") Then
            phone = String.Format("011{0}", Right(phone, phone.Length - 1))
        End If
        For iCtr = 0 To phone.Length - 1
            If InStr(sValidString, phone.Substring(iCtr, 1)) > 0 Then
                result = result & phone.Substring(iCtr, 1)
            End If
        Next

        If result = Nothing Then
            result = ""
        End If
        FilterPhone = result
    End Function
    Public Shared Function IsPhone(ByVal phone As String) As Boolean
        Dim temp As String = ""
        Dim result As Boolean = True
        Dim phoneRegex As String = "\d{10}"
        temp = Util.FilterPhone(phone.Trim)
        If Left(phone.Trim, 1) <> "0" Then
            If Not Regex.IsMatch(temp, phoneRegex) Then
                result = False
            End If
            If (temp.Length <> 10) Then
                result = False
            End If
        End If
        IsPhone = result
    End Function
    Public Shared Function IsPhone(ByVal vPhone As String, ByVal bCheckEmpty As Boolean) As Boolean
        Dim result As Boolean = True
        Dim phone As String = ""
        phone = Util.FilterPhone(vPhone)
        If (bCheckEmpty = True) Then
            result = IsPhone(phone)
        Else
            If phone.Trim = "" Then
                result = True
            Else
                result = IsPhone(phone)
            End If
        End If
        IsPhone = result
    End Function
    Public Shared Function DateFormat(ByVal vDate As String)
        Dim arr As Array
        arr = Split(vDate, "/")
        If Len(arr(0)) < 2 Then arr(0) = "0" & arr(0)
        If Len(arr(1)) < 2 Then arr(1) = "0" & arr(1)
        DateFormat = arr(0) & "/" & arr(1) & "/" & arr(2)
    End Function

    

    Public Shared Function HideCardNumber(ByVal cardNumber As String, Optional ByVal iPaymethod As Integer = -1) As String
        Dim result As String = ""
        Try
            'If iPaymethod = 4 Then
            '    result = cardNumber
            'Else
            '    result = Left(cardNumber, 4)
            '    For i As Integer = 4 To cardNumber.Length - 5
            '        result = String.Format("{0}X", result)
            '    Next
            '    result = String.Format("{0}{1}", result, Right(cardNumber, 4))
            'End If
            result = HideCardNumberForLiveryCoachCer(cardNumber, iPaymethod)
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return result
    End Function
    Public Shared Function DoDuration(ByVal PickUpDate As DateTime, ByVal DropOffDate As DateTime) As String
        Dim minutes As Integer
        Dim hours As Integer
        minutes = DateDiff("n", PickUpDate, DropOffDate)
        hours = minutes / 60
        DoDuration = CStr(hours)
    End Function
    Public Shared Function IsExistedPassengers(ByVal dt As DataTable, ByVal name As String) As Boolean
        Dim count As Integer = dt.Rows.Count
        Dim i As Integer = 0
        Dim result As Boolean = False
        While i < count
            'If dt.Rows(i).Item(0) = companyStr And dt.Rows(i).Item(1) = cus.FirstName + " " + cus.LastName _
            'And dt.Rows(i).Item(2) = cus.MobilePhone Then
            If dt.Rows(i).Item(1) = name Then
                result = True
                i = count
            End If
            i = i + 1
        End While
        IsExistedPassengers = result
    End Function
    Public Shared Function AddPassengerToGrid(ByVal maxOccupancy As Integer, ByVal companyName As String, ByVal name As String, _
            ByVal phone As String, ByVal customerID As Integer, ByRef dt As DataTable) As Boolean
        Dim count As Integer = dt.Rows.Count
        Dim i As Integer = 0
        Dim flag As Boolean = False
        While i < count
            If dt.Rows(i).Item(1).Equals("") Then
                dt.Rows(i).Item(0) = companyName
                dt.Rows(i).Item(1) = name
                dt.Rows(i).Item(2) = phone
                dt.Rows(i).Item(3) = customerID
                i = count
                flag = True
            Else
                i = i + 1
            End If
        End While
        If flag = False Then
            If dt.Rows.Count < maxOccupancy Then
                dt.Rows.Add(companyName, name, phone, customerID)
                flag = True
            End If
        End If
        Return flag
    End Function
    Public Shared Function IsEmptyList(ByVal grid As GridView) As Boolean
        Dim count As Integer = grid.Rows.Count
        Dim i As Integer = 0
        Dim result As Boolean = True
        While (i < count)
            Dim txtName As TextBox = grid.Rows(i).FindControl("txtName")
            If Not txtName.Text.Equals("") Then
                result = False
                i = count
            End If
            i = i + 1
        End While
        IsEmptyList = result
    End Function

    Public Shared Function IsEmptyList(ByVal dt As DataTable, ByVal fieldName As String) As Boolean
        Dim count As Integer = dt.Rows.Count
        Dim i As Integer = 0
        Dim result As Boolean = True
        While (i < count)
            Dim name As String = dt.Rows(i)(fieldName)
            If Not name.Equals("") Then
                result = False
                i = count
            End If
            i = i + 1
        End While
        IsEmptyList = result
    End Function

    Public Shared Function IsExistedPassengers(ByVal grid As GridView) As Boolean
        Dim count As Integer = grid.Rows.Count
        Dim i As Integer = 0, j As Integer = 0
        Dim result As Boolean = False
        For i = 0 To grid.Rows.Count - 1
            For j = i + 1 To grid.Rows.Count - 1
                Dim txtName As TextBox = grid.Rows(i).FindControl("txtName")
                Dim txtName1 As TextBox = grid.Rows(j).FindControl("txtName")
                If Not txtName.Text.Equals("") Then
                    If txtName.Text = txtName1.Text Then
                        result = True
                    End If
                End If
            Next
        Next
        IsExistedPassengers = result
    End Function

    Public Shared Function IsExistedName(ByVal dt As DataTable, ByVal fieldName As String) As Boolean
        Dim count As Integer = dt.Rows.Count
        Dim i As Integer = 0, j As Integer = 0
        Dim result As Boolean = False
        For i = 0 To dt.Rows.Count - 1
            For j = i + 1 To dt.Rows.Count - 1
                Dim name As String = dt.Rows(i)(fieldName)
                Dim name1 As String = dt.Rows(j)(fieldName)
                If Not name.Equals("") Then
                    If name = name1 Then
                        result = True
                    End If
                End If
            Next
        Next
        IsExistedName = result
    End Function

    Public Shared Function GetRemoteIP() As String
        Return HttpContext.Current.Request.ServerVariables("REMOTE_ADDR").ToString
    End Function

    ' Tests for empty required field data
    Public Shared Function IsEmpty(ByVal InputString As String) As String
        If InputString = "" Then
            IsEmpty = True
        Else
            IsEmpty = False
        End If
    End Function

    Public Shared Function SendMail(ByVal addressesCc As String, ByVal addressesTo As String, ByVal subject As String, ByVal content As String) As String
        Dim errMessage As String = ""
        Try
            Dim mail As New MailMessage()

            Dim addressFrom As String = GetConfigKey("ServerMail", WebConfigServer.GetValueWebConfigByKey("email_contact"))
            Dim MailServer As String = GetConfigKey("SMTPHost", WebConfigServer.GetValueWebConfigByKey("smtp"))
            Dim MailPort As String = GetConfigKey("SMTPPort", WebConfigServer.GetValueWebConfigByKey("port"))
            Dim MailUserName As String = GetConfigKey("SMTPUsername", WebConfigServer.GetValueWebConfigByKey("email_contact"))
            Dim MailPassword As String = GetConfigKey("SMTPPassword", WebConfigServer.GetValueWebConfigByKey("pass_email_contact"))
            Dim mailSSL As String = Util.GetConfigKey("SMTPSSL", "1")

            Dim arrData As String()
            Dim iCtr As Integer = 0

            'set the addresses
            mail.From = New MailAddress(addressFrom)
            addressesTo = Replace(addressesTo, vbNewLine, ";")
            addressesTo = Replace(addressesTo, ",", ";")
            arrData = Split(addressesTo, ";")
            For iCtr = 0 To arrData.Length - 1
                If Not arrData(iCtr).Trim.Equals("") Then
                    mail.To.Add(arrData(iCtr))
                End If
            Next

            If addressesCc <> "" Then
                addressesCc = Replace(addressesCc, ",", ";").Replace(vbNewLine, ";")
                arrData = Split(addressesCc, ";")
                For iCtr = 0 To arrData.Length - 1
                    If Not arrData(iCtr).Trim.Equals("") Then
                        mail.CC.Add(arrData(iCtr))
                    End If
                Next
            End If

            'set the content
            mail.Subject = subject
            mail.Body = content
            mail.IsBodyHtml = True

            'send the message
            Dim smtp As New SmtpClient(MailServer, MailPort)
            If mailSSL = "1" Then
                smtp.EnableSsl = True
            End If
            smtp.Credentials = New System.Net.NetworkCredential(MailUserName, MailPassword)

            smtp.Send(mail)
            mail.Dispose()
            smtp = Nothing
        Catch ex As Exception
            errMessage = ex.Message
        End Try

        Return errMessage
    End Function


   
    Public Shared Sub CreateConfigKey(ByVal key As String, ByVal defaultValue As String)
        Try
            Dim path As String = HttpContext.Current.Server.MapPath("~/web.config")
            Dim xDoc As XmlDocument = New XmlDocument()
            xDoc.Load(path)
            Dim nodeList As XmlNodeList = xDoc.GetElementsByTagName("appSettings")
            Dim nodeAppSettings As XmlNodeList = nodeList(0).ChildNodes
            Dim accountNum As XmlElement = xDoc.CreateElement("add")
            Dim anAttrKey As XmlAttribute = xDoc.CreateAttribute("key")
            accountNum.Attributes.Append(anAttrKey)
            Dim anAttrValue As XmlAttribute = xDoc.CreateAttribute("value")
            accountNum.Attributes.Append(anAttrValue)
            Dim xmlAttCollection As XmlAttributeCollection = accountNum.Attributes
            xmlAttCollection(0).InnerXml = key
            xmlAttCollection(1).InnerXml = defaultValue
            nodeList(0).AppendChild(accountNum)
            xDoc.Save(path)
        Catch ex As Exception
            log.Error("Util - CreateConfigKey: ERROR->" + ex.ToString)
        End Try
    End Sub


    Public Shared Function GetConfigKey(ByVal key As String, Optional ByVal defaultValue As String = "", Optional ByVal notBank As Boolean = False) As String
        Dim value As String = ""
        If ConfigurationManager.AppSettings(key) Is Nothing Then
            CreateConfigKey(key, defaultValue)
            value = defaultValue
        Else
            value = ConfigurationManager.AppSettings(key)
            If notBank AndAlso value.Trim.Equals("") Then
                value = defaultValue
            End If
        End If
        Return value.Trim
    End Function

 
    Public Shared Function SetConfigKey(ByRef myConfiguration As System.Configuration.Configuration, ByVal key As String, ByVal value As String) As Boolean
        Dim status As Boolean = False
        'Dim myConfiguration As Configuration.Configuration = OpenWebConfiguration("~")
        Try
            value = value.Trim
            If myConfiguration.AppSettings.Settings.Item(key) Is Nothing Then
                ''Util.CreateConfigKey(key, value)
                myConfiguration.AppSettings.Settings.Add(key, value)
            Else
                myConfiguration.AppSettings.Settings.Item(key).Value = value
            End If
            status = True
        Catch ex As Exception
            log.Error("Util - SetConfigKey: ERROR->" + ex.ToString)
        End Try
        Return status
    End Function

    Public Shared Function HashData(ByVal sCode As String, ByVal sValue As String) As String
        Dim X As Integer
        Dim HashedData As String
        HashData = ""
        HashedData = ""
        For X = 1 To Len(sValue)
            HashedData = HashedData + Chr(Asc(Mid(sValue, X, 1)) + 96 - Asc(UCase(Mid(sCode, 1, 1))))
        Next X
        HashData = Replace(HashedData, "'", "[[!]]")
    End Function

    Public Shared Function UnHashData(ByVal sCode As String, ByVal sValue As String) As String
        Dim X As Integer
        Dim UnHashedData As String
        UnHashData = ""
        UnHashedData = ""
        sValue = Replace(sValue, "[[!]]", "'")
        For X = 1 To Len(sValue)
            UnHashedData = UnHashedData + Chr(Asc(Mid(sValue, X, 1)) - 96 + Asc(UCase(Mid(sCode, 1, 1))))
        Next (X)
        UnHashData = UnHashedData

    End Function

 
   
    Public Shared Function GetColumnIdentity(ByVal tableName As String) As String
        Dim columnName As String = ""
        Try
            Dim sql As String = String.Format("select name from sys.columns where is_identity = 1 and object_name(object_id) = '{0}'", tableName)
            Dim reader As SqlDataReader = Connection.ExcuteReader(sql)
            If reader.Read Then
                columnName = reader.GetValue(0)
            End If
            reader.Close()
            Connection.Close()
        Catch ex As Exception
            Connection.CheckCloseConnect()
            log.Error(ex)
        End Try
        Return columnName
    End Function

    Public Shared Function CheckHideCardNumber(ByVal creditCardNumber As String) As Boolean
        Dim result As Boolean = False
        creditCardNumber = creditCardNumber.Trim
        Dim counter As Integer = 0
        For i As Integer = 0 To creditCardNumber.Length - 1
            If creditCardNumber.Substring(i, 1).Equals("X") Then
                counter = counter + 1
            End If
        Next
        If counter > 0 Then
            result = True
        End If
        Return result
    End Function

 

    Public Shared Function EnscriptPassword(ByVal psw As String) As String
        Dim result As String = psw.Length.ToString()
        For i As Integer = 0 To psw.Length - 1
            If IsNumeric(psw(i)) Then
                result = String.Format("{0}[!]{1}", result, Integer.Parse(psw(i)) * psw.Length)
            Else
                result = String.Format("{0}[!]{1}", result, psw(i))
            End If
        Next
        Return result
    End Function

   

    Public Shared Function RemoveBadChar(ByVal strInput As String, Optional ByVal replaceBy As String = "_") As String
        Return Regex.Replace(strInput, "[^A-Za-z0-9]", replaceBy)
    End Function

    Public Shared Function GetDictionaryValueByKey(ByVal dictionaryObject As Dictionary(Of String, Object), ByVal key As String) As Object
        Dim value As Object = Nothing
        Try
            If dictionaryObject.ContainsKey(key) Then
                value = EscapeQuotes(dictionaryObject.Item(key)).Trim
            Else
                value = ""
            End If

        Catch ex As Exception
            log.Error(ex)
        End Try
        Return value
    End Function

    Public Shared Sub SetDictionaryValueByKey(ByRef dictionaryObject As Dictionary(Of String, Object), ByVal key As String, ByVal value As Object)
        Try
            If dictionaryObject.ContainsKey(key) Then
                dictionaryObject.Item(key) = value
            Else
                dictionaryObject.Add(key, value)
            End If
        Catch ex As Exception
            log.Error(ex)
        End Try
    End Sub

    Public Shared Sub SetSessionData(ByVal key As String, ByVal objData As Object)
        HttpContext.Current.Session(key) = objData

    End Sub
    Public Shared Function GetSessionData(ByVal key As String, Optional ByVal isRemoveData As Boolean = True) As Object
        Dim objData As Object = HttpContext.Current.Session(key)
        If isRemoveData Then
            HttpContext.Current.Session(key) = Nothing
        End If
        Return objData
    End Function

   

    Public Shared Function HideCardNumberForLiveryCoachCer(ByVal cardNumber As String, ByVal payMethod As Integer) As String
        Dim result As String = ""
        Try
            result = cardNumber
            If payMethod <> 4 Then
                result = Left(cardNumber, 4)
                For i As Integer = 4 To cardNumber.Length - 5
                    result = String.Format("{0}X", result)
                Next
                result = String.Format("{0}{1}", result, Right(cardNumber, 4))
            End If
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return result
    End Function

    Public Shared Sub CreateStoreProcGetTripID()
        Try
            Dim sql As String = "if not exists(Select * from sys.objects where type_desc = 'SQL_STORED_PROCEDURE' AND name = 'ReturnNextAvailableTripID')"
            sql = String.Format("{0} begin EXEC dbo.sp_executesql @statement = N' ", sql)
            sql = String.Format("{0} CREATE PROCEDURE ReturnNextAvailableTripID AS BEGIN set nocount on ", sql)
            sql = String.Format("{0} declare @TripID int; declare @ResDetailCount int; set @TripID = 0; set @ResDetailCount = 1; ", sql)
            sql = String.Format("{0} while @TripID = 0 Begin ", sql)
            sql = String.Format("{0} select @TripID = NextSeqTripID from DefaultConfigs; ", sql)
            sql = String.Format("{0} update DefaultConfigs set NextSeqTripID = NextSeqTripID + 1; ", sql)
            sql = String.Format("{0} select @ResDetailCount = count(*) from reservations where tripid = @TripID; ", sql)
            sql = String.Format("{0} if @ResDetailCount > 0 begin set @TripID = 0 end ", sql)
            sql = String.Format("{0} end end return @TripID' end ", sql)
            Connection.ExcuteQuery(sql)
        Catch ex As Exception
            log.Error(ex)
        End Try
    End Sub

    Public Shared Function IsExitsVehicleTypeImage(ByVal fileName As String) As Boolean

        Dim isExists As Boolean = False
        Dim webRequest As WebRequest
        Dim webResponse As WebResponse
        Try
            If fileName.ToUpper.IndexOf("HTTP://") > -1 Or fileName.ToUpper.IndexOf("HTTPS://") > -1 Then
                webRequest = webRequest.Create(fileName)
                webResponse = webRequest.GetResponse()
                isExists = True
            Else
                If File.Exists(HttpContext.Current.Server.MapPath(fileName)) Then
                    isExists = True
                End If
            End If
        Catch ex As Exception
            Return False
        End Try
        Return isExists
    End Function

    Public Shared Function CalculatorFromString(ByVal strCal As String, ByVal defaultValue As Double) As Object
        Dim result As Object = defaultValue
        Try
            If Not strCal.Trim.Equals("") Then
                result = New DataTable().Compute(strCal, Nothing)
            End If
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return result
    End Function

    Public Shared Function ConvertStringDateToNewStringDate(ByVal strDate As String, ByVal strFormatDate As String) As String
        Dim result As String = ""
        Try
            Dim dt As DateTime = Convert.ToDateTime(strDate)
            result = dt.ToString(strFormatDate)
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return result
    End Function

    Public Shared Function IsDateTime(ByVal strDate As String) As Boolean
        Dim flag As Boolean = False
        Try
            If IsDate(strDate) Then
                Dim temp As String = Format(CDate(strDate), "MM/dd/yyyy")
                temp = temp.Replace("01/01/1990", "").Replace("01/01/1900", "").Replace("01/01/1010", "").Replace("01/01/0001", "")
                Dim dateForStr As Date = strDate
                If dateForStr.Year.Equals("1900") Then
                    temp = ""
                End If
                If Not temp.Equals("") Then
                    flag = True
                End If
            End If
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return flag
    End Function

    Public Shared Function GetStrThuTrongTuan(ByVal thuTrongTuan As Integer) As String
        Dim result As String = "CN"
        Try
            Select Case thuTrongTuan
                Case 1 : result = "Thứ Hai"
                Case 2 : result = "Thứ Ba"
                Case 3 : result = "Thứ Tư"
                Case 4 : result = "Thứ Năm"
                Case 5 : result = "Thứ Sáu"
                Case 6 : result = "Thứ Bảy"
                Case Else : result = "CN"
            End Select

        Catch ex As Exception
            ''Throw ex
        End Try
        Return result
    End Function

    Public Shared Function GetThuTrongTuan(ByVal thuTrongTuan As Integer, Optional string_cn As String = "CN") As String
        Dim result As String = string_cn
        Try
            Select Case thuTrongTuan
                Case 1 : result = "Thứ 2"
                Case 2 : result = "Thứ 3"
                Case 3 : result = "Thứ 4"
                Case 4 : result = "Thứ 5"
                Case 5 : result = "Thứ 6"
                Case 6 : result = "Thứ 7"
                Case Else : result = string_cn
            End Select

        Catch ex As Exception
            ''Throw ex
        End Try
        Return result
    End Function

End Class
